package com.kintreda.service.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kintreda.common.config.R;
import com.kintreda.common.config.exception.CommonBaseErrorCode;
import com.kintreda.common.config.exception.CommonBaseException;
import com.kintreda.common.mybatis.entity.SysRole;
import com.kintreda.common.mybatis.entity.SysRoleMenu;
import com.kintreda.common.mybatis.model.BasePageModel;
import com.kintreda.common.mybatis.model.RoleAuthModel;
import com.kintreda.common.mybatis.service.ISysMenuService;
import com.kintreda.common.mybatis.service.ISysRoleMenuService;
import com.kintreda.common.mybatis.service.ISysRoleService;
import com.kintreda.common.mybatis.vos.ManagerMenuVo;
import com.kintreda.common.oauth.annotation.SetLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/platform/role")
@Api(tags = "角色")
public class RoleController {

    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private ISysRoleMenuService iSysRoleMenuService;
    @Autowired
    private ISysMenuService iSysMenuService;

    @ApiOperation(value = "角色管理")
    @GetMapping("/list")
    public R<IPage<SysRole>> role(BasePageModel param){
        IPage<SysRole> page = new Page<>(param.getPage(),param.getLimit());
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(param.getKeyword()) && !"".equals(param.getKeyword())){
            queryWrapper.like("name",param.getKeyword());
        }
        IPage<SysRole> result = iSysRoleService.page(page, queryWrapper);
        return R.ok(result);
    }

    @ApiOperation(value = "保存")
    @PostMapping("/save")
    @SetLog("添加或修改角色信息")
    public R<Boolean> save(@Valid @RequestBody SysRole sysRole){
        iSysRoleService.saveOrUpdate(sysRole);
        return R.ok();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("/del/{roleId}")
    @SetLog("删除角色")
    @Transactional
    public R<Boolean> del(@PathVariable Integer roleId){
        try {
            iSysRoleMenuService.removeByRoleId(roleId);
            iSysRoleService.removeById(roleId);
            return R.ok(roleId);
        }catch (Exception e){
            throw new CommonBaseException(CommonBaseErrorCode.DEL_FAIL);
        }
    }

    @ApiOperation(value = "权限列表")
    @GetMapping("/menu/{roleId}")
    public R<List<ManagerMenuVo>> menu(@PathVariable Integer roleId,String group){
        Collection<Integer> menuIds = iSysRoleMenuService.getMenuIdsByRoleId(roleId,group);
        List<ManagerMenuVo> treeList = iSysMenuService.getTreeList(0, group, menuIds);
        return R.ok(treeList);
    }

    @ApiOperation(value = "获取权限菜单Id")
    @GetMapping("/authorize")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "com/kintreda/service/platform",value = "平台",required = true),
            @ApiImplicitParam(name = "roleId",value = "角色Id",required = true)
    })
    public R<Collection<Integer>> authorize(Integer roleId,String platform){
        Collection<Integer> menuIdsByRoleId = iSysRoleMenuService.getMenuIdsByRoleId(roleId, platform);
        return R.ok(menuIdsByRoleId);
    }


    @ApiOperation(value = "角色授权")
    @PostMapping("/auth")
    @SetLog("修改角色授权")
    @Transactional
    public R<Boolean> auth(@Valid @RequestBody RoleAuthModel param){
        try {
            //删除原来的授权
            iSysRoleMenuService.removeByRoleId(param.getRoleId());
            //权限集合
            List<SysRoleMenu> roleMenus = new ArrayList<>();
            //增加新权限
            param.getRoles().forEach(r->{
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setMenuId(r);
                sysRoleMenu.setRoleId(param.getRoleId());
                roleMenus.add(sysRoleMenu);
            });
            iSysRoleMenuService.saveBatch(roleMenus);
            return R.ok();
        }catch (Exception e){
            throw new CommonBaseException(CommonBaseErrorCode.ROLE_AUTH_FAIL);
        }
    }

}
